<script setup>
import api from '../api/notification_api.js'
import userApi from '../api/user_api.js'
import { ref, onMounted } from "vue";
import { ElMessageBox } from "element-plus";
import lodash from 'lodash'

// 数据定义区域
const tableData = ref([]);
const total = ref(0);
const editWinVisible = ref(false);
const userSelectVisible = ref(false); // 用户选择对话框
const users = ref([]); // 用户列表
const selectedUsers = ref([]); // 选中的用户

const loginUser = ref({
  role: localStorage.getItem("role") || "admin", // 默认为admin，实际应该从登录信息中获取
  id: localStorage.getItem("userId") || null
});

const searchObj = ref({
  current: 1,
  limit: 10,
  user_id: '',
  title: '',
});

const obj = ref({});

// 查询方法
const search = async () => {
  const result = await api.pageWithDetails(searchObj.value);
  tableData.value = result.data;
  total.value = result.count;
};

// 获取所有用户用于选择
const loadUsers = async () => {
  try {
    const result = await userApi.page({ current: 1, limit: 9999 });
    users.value = result.data || [];
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessageBox.alert('获取用户列表失败: ' + (error.message || '未知错误'), '提示', { type: 'error' });
  }
};

// 选择用户
const selectUsers = () => {
  selectedUsers.value = [...obj.value.user_ids || []];
  userSelectVisible.value = true;
};

// 确认选择用户
const confirmUserSelection = () => {
  obj.value.user_ids = [...selectedUsers.value];
  obj.value.user_id = selectedUsers.value.join(','); // 用于显示
  userSelectVisible.value = false;
};

// 取消选择用户
const cancelUserSelection = () => {
  userSelectVisible.value = false;
};

// 通过ID获取用户信息
const getUserById = (userId) => {
  return users.value.find(user => user.id == userId);
};

// 移除选中的用户
const removeUser = (userId) => {
  const index = obj.value.user_ids.indexOf(userId);
  if (index > -1) {
    obj.value.user_ids.splice(index, 1);
    // 更新显示字段
    obj.value.user_id = obj.value.user_ids.join(',');
  }
};

onMounted(async () => {
  await search();
});

const editCancel = () => {
  obj.value = {};
  editWinVisible.value = false;
};

const editCommit = async () => {
  if (obj.value.id) {
    await api.edit(obj.value);
  } else {
    // 发送给多个用户
    if (obj.value.user_ids && obj.value.user_ids.length > 0) {
      // 创建多个通知
      const promises = obj.value.user_ids.map(userId => {
        const notification = {
          user_id: userId,
          title: obj.value.title,
          content: obj.value.content,
          is_read: 0
        };
        return api.add(notification);
      });
      await Promise.all(promises);
    } else {
      // 发送给单个用户或所有用户
      await api.add(obj.value);
    }
  }
  search();
  editWinVisible.value = false;
};

const handleSearch = () => {
  searchObj.value.current = 1;
  search();
};

const handleSizeChange = (val) => {
  searchObj.value.limit = val;
  search();
};

const handleCurrentChange = (val) => {
  searchObj.value.current = val;
  search();
};

const handleAdd = () => {
  obj.value = {
    user_id: '', // 用于显示的字段
    user_ids: [], // 实际存储选中用户ID的数组
    title: '',
    content: '',
    is_read: 0,  // 默认未读
  };
  editWinVisible.value = true;
};

const handleEdit = (index, row) => {
  obj.value = lodash.clone(row);
  editWinVisible.value = true;
};

const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该通知吗？',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error'
      }
  )
      .then(async () => {
        await api.del(row.id);
        searchObj.value.current = 1;
        search();
      })
      .catch(() => {});
};
// 点击标题显示内容并标记为已读
const toggleContent = async (row) => {
  // 如果原来是未读状态，更新为已读
  if (!isAdminLogin()&&row.is_read === 0) {
    const updatedRow = lodash.clone(row);
    updatedRow.is_read = 1;
    await api.edit(updatedRow);
    // 更新本地数据
    row.is_read = 1;
  }
};

const isAdminLogin = () => {
  return loginUser.value.role === 'admin';
}
</script>

<template>
  <div class="notification-management-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchObj" style="margin-top: 10px; margin-bottom: 15px;">
      <el-form-item label="用户名">
        <el-input v-model="searchObj.username" placeholder="请输入用户名" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item label="标题">
        <el-input v-model="searchObj.title" placeholder="请输入标题" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </el-form-item>
      <el-form-item v-if="isAdminLogin()">
        <el-button type="primary" @click="handleAdd">发布</el-button>
      </el-form-item>
    </el-form>

    <!-- 通知表格 -->
    <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px;"
        border
        stripe
        :header-cell-style="{ 'background-color': '#f5f7fa', 'font-weight': 'bold' }"
    >
<!--      <el-table-column label="ID" width="80" align="center">-->
<!--        <template #default="scope">-->
<!--          {{ scope.row.id }}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="用户" min-width="120">
        <template #default="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="标题" min-width="180">
        <template #default="scope">
          <span
              v-if="!isAdminLogin()"
              class="notification-title"
              :class="{ 'unread': scope.row.is_read === 0 }"
              @click="toggleContent(scope.row)"
          >
            {{ scope.row.title }}
          </span>
          <span v-else>{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="内容" min-width="300">
        <template #default="scope">
          <span v-if="isAdminLogin()">{{ scope.row.content }}</span>
          <span v-else-if="scope.row.is_read === 1">{{ scope.row.content }}</span>
          <span v-else>点击标题查看内容</span>
        </template>
      </el-table-column>
      <el-table-column label="是否已读" min-width="120">
        <template #default="scope">
          <el-tag :type="scope.row.is_read === 1 ? 'success' : 'info'">
            {{ scope.row.is_read === 1 ? '已读' : '未读' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column  label="操作" min-width="180" align="center">
        <template #default="scope">
          <el-button v-if="isAdminLogin()" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              style="margin-left: 5px;"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10, 20, 30, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="text-align: right; margin-top: 10px;"
    />

    <!-- 编辑/新增对话框 -->
    <el-dialog v-model="editWinVisible" :title="obj.id ? '编辑通知信息' : '发布通知'" width="600px">
      <el-form :model="obj" label-width="100px">
        <el-form-item label="ID" v-if="obj.id">
          <el-input v-model="obj.id" disabled />
        </el-form-item>
        <el-form-item label="用户">
          <el-input
            v-model="obj.user_id"
            autocomplete="off"
            placeholder="点击选择用户"
            readonly
            @click="loadUsers().then(() => selectUsers())"
          >
            <template #append>
              <el-button @click="loadUsers().then(() => selectUsers())">选择</el-button>
            </template>
          </el-input>
          <div v-if="obj.user_ids && obj.user_ids.length > 0" style="margin-top: 10px;">
            <el-tag
              v-for="userId in obj.user_ids"
              :key="userId"
              closable
              @close="removeUser(userId)"
              style="margin-right: 5px; margin-bottom: 5px;"
            >
              {{ getUserById(userId)?.username || userId }}
            </el-tag>
          </div>
          <div v-else-if="!obj.id" style="margin-top: 10px;">
            <el-text type="info">未选择用户，通知将发送给所有用户</el-text>
          </div>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="obj.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input type="textarea" v-model="obj.content" autocomplete="off" rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editCancel">取消</el-button>
          <el-button type="primary" @click="editCommit">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户选择对话框 -->
    <el-dialog v-model="userSelectVisible" title="选择用户" width="800px">
      <el-table
        :data="users"
        height="400"
        @selection-change="selectedUsers = $event.map(user => user.id)"
        :row-key="row => row.id"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="用户ID" width="80"></el-table-column>
        <el-table-column prop="username" label="用户名" min-width="150"></el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="200"></el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelUserSelection">取消</el-button>
          <el-button type="primary" @click="confirmUserSelection">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.notification-title {
  cursor: pointer;
  color: #409eff;
}

.notification-title.unread {
  font-weight: bold;
}
</style>
